package com.abc.util;

import com.abc.model.ChatMessageModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息链路管理工具类
 * 用于维护消息的父子关系链路，每个消息只存储从根到当前消息的路径
 */
@Slf4j
@Component
public class MessageChainUtil {
    
    @Autowired
    private MongoTemplate mongoTemplate;
    
    /**
     * 根据父消息ID构建消息链路
     * 如果父消息ID为空，则当前消息为根消息，链路只包含自己
     *
     * @param sessionId 会话ID
     * @param username 用户名
     * @param parentMessageId 父消息ID，如果为null则表示根消息
     * @param currentMessageId 当前消息ID
     * @return 从根消息到当前消息的链路
     */
    public List<String> buildMessageChainFromParent(String sessionId, String username, String parentMessageId, String currentMessageId) {
        try {
            List<String> chain = new ArrayList<>();
            
            // 如果没有父消息，当前消息就是根消息
            if (parentMessageId == null || parentMessageId.trim().isEmpty()) {
                chain.add(currentMessageId);
                return chain;
            }
            
            // 查找父消息
            ChatMessageModel parentMessage = findMessageById(sessionId, username, parentMessageId);
            if (parentMessage == null) {
                log.warn("找不到父消息, parentMessageId: {}, 将当前消息设为根消息", parentMessageId);
                chain.add(currentMessageId);
                return chain;
            }
            
            // 如果父消息有链路，使用父消息的链路
            if (parentMessage.getMessageChain() != null && !parentMessage.getMessageChain().isEmpty()) {
                chain.addAll(parentMessage.getMessageChain());
            } else {
                // 如果父消息没有链路，递归构建
                chain = buildChainRecursively(sessionId, username, parentMessageId);
            }
            
            // 添加当前消息到链路末尾
            chain.add(currentMessageId);
            
            return chain;
            
        } catch (Exception e) {
            log.error("构建消息链路失败, sessionId: {}, username: {}, parentMessageId: {}, currentMessageId: {}, 错误: {}", 
                     sessionId, username, parentMessageId, currentMessageId, e.getMessage(), e);
            // 发生错误时，返回只包含当前消息的链路
            List<String> fallbackChain = new ArrayList<>();
            fallbackChain.add(currentMessageId);
            return fallbackChain;
        }
    }
    
    /**
     * 根据消息ID查找消息
     *
     * @param sessionId 会话ID
     * @param username 用户名
     * @param messageId 消息ID
     * @return 消息对象，如果找不到返回null
     */
    private ChatMessageModel findMessageById(String sessionId, String username, String messageId) {
        try {
            Query query = Query.query(
                    Criteria.where("session_id").is(sessionId)
                            .and("username").is(username)
                            .and("message_id").is(messageId)
            );
            
            return mongoTemplate.findOne(query, ChatMessageModel.class);
            
        } catch (Exception e) {
            log.error("查找消息失败, sessionId: {}, username: {}, messageId: {}, 错误: {}", 
                     sessionId, username, messageId, e.getMessage(), e);
            return null;
        }
    }

    /**
     * 递归构建消息链路
     *
     * @param sessionId 会话ID
     * @param username 用户名
     * @param messageId 当前消息ID
     * @return 从根消息到当前消息的链路
     */
    private List<String> buildChainRecursively(String sessionId, String username, String messageId) {
        List<String> chain = new ArrayList<>();
        
        ChatMessageModel message = findMessageById(sessionId, username, messageId);
        if (message == null) {
            return chain;
        }
        
        // 如果有父消息，先构建父消息的链路
        if (message.getParentMessageId() != null && !message.getParentMessageId().trim().isEmpty()) {
            chain.addAll(buildChainRecursively(sessionId, username, message.getParentMessageId()));
        }
        
        // 添加当前消息
        chain.add(messageId);
        
        return chain;
    }

    /**
     * 获取会话中最后一条消息的ID，用于确定新消息的父消息
     *
     * @param sessionId 会话ID
     * @param username 用户名
     * @return 最后一条消息的ID，如果没有消息返回null
     */
    public String getLastMessageId(String sessionId, String username) {
        try {
            Query query = Query.query(
                    Criteria.where("session_id").is(sessionId)
                            .and("username").is(username)
            ).with(org.springframework.data.domain.Sort.by(
                    org.springframework.data.domain.Sort.Direction.DESC, "create_time"
            )).limit(1);
            
            ChatMessageModel lastMessage = mongoTemplate.findOne(query, ChatMessageModel.class);
            
            return lastMessage != null ? lastMessage.getMessageId() : null;
            
        } catch (Exception e) {
            log.error("获取最后消息ID失败, sessionId: {}, username: {}, 错误: {}", 
                     sessionId, username, e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 获取会话中最新消息的链路
     *
     * @param sessionId 会话ID
     * @param username 用户名
     * @return 最新的消息链路，如果没有消息则返回空列表
     */
    public List<String> getLatestMessageChain(String sessionId, String username) {
        try {
            Query query = Query.query(
                    Criteria.where("session_id").is(sessionId)
                            .and("username").is(username)
                            .and("message_chain").ne(null)
            ).with(org.springframework.data.domain.Sort.by(
                    org.springframework.data.domain.Sort.Direction.DESC, "create_time"
            )).limit(1);
            
            ChatMessageModel latestMessage = mongoTemplate.findOne(query, ChatMessageModel.class);
            
            if (latestMessage != null && latestMessage.getMessageChain() != null) {
                return new ArrayList<>(latestMessage.getMessageChain());
            }
            
            return new ArrayList<>();
            
        } catch (Exception e) {
            log.error("获取最新消息链路失败, sessionId: {}, username: {}, 错误: {}", 
                     sessionId, username, e.getMessage(), e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 清理会话的消息链路（将所有消息的链路字段和父消息ID设为null）
     *
     * @param sessionId 会话ID
     * @param username 用户名
     */
    public void clearMessageChainForSession(String sessionId, String username) {
        try {
            Query query = Query.query(
                    Criteria.where("session_id").is(sessionId)
                            .and("username").is(username)
            );
            
            Update update = Update.update("message_chain", null)
                                  .set("parent_message_id", null);
            
            mongoTemplate.updateMulti(query, update, ChatMessageModel.class);
            
            log.debug("清理会话消息链路成功, sessionId: {}, username: {}", sessionId, username);
            
        } catch (Exception e) {
            log.error("清理会话消息链路失败, sessionId: {}, username: {}, 错误: {}", 
                     sessionId, username, e.getMessage(), e);
        }
    }
}
